<?php
/**
 * This file is part of workerman.
 *
 * Licensed under The MIT License
 * For full copyright and license information, please see the MIT-LICENSE.txt
 * Redistributions of files must retain the above copyright notice.
 *
 * @author walkor<walkor@workerman.net>
 * @copyright walkor<walkor@workerman.net>
 * @link http://www.workerman.net/
 * @license http://www.opensource.org/licenses/mit-license.php MIT License
 */

/**
 * 用于检测业务代码死循环或者长时间阻塞等问题
 * 如果发现业务卡死，可以将下面declare打开（去掉//注释），并执行php start.php reload
 * 然后观察一段时间workerman.log看是否有process_timeout异常
 */
//declare(ticks=1);

use \GatewayWorker\Lib\Gateway;

/**
 * 主逻辑
 * 主要是处理 onConnect onMessage onClose 三个方法
 * onConnect 和 onClose 如果不需要可以不用实现并删除
 */
class Events
{

  public static function wrapMsg($msg_name, $msg_body){
        $json_encode_msg = json_encode($msg_body);
        return "$msg_name$json_encode_msg";
  }

    /**
     * 当客户端连接时触发
     * 如果业务不需此回调可以删除onConnect
     * 
     * @param int $client_id 连接id
     */
    public static function onConnect($client_id)
    {

        // 向当前client_id发送数据 
        Gateway::sendToClient($client_id, static::wrapMsg("connect_s2c", array('err_no' => 0, 'client_id' => "$client_id")));
        // 向所有人发送
        //Gateway::sendToAll("$client_id login\r\n");

        //static::RequestAccessToken();
        if(!isset($GLOBALS["AccessToken"]))
          static::RequestAccessToken();
    }
    
   /**
    * 当客户端发来消息时触发
    * @param int $client_id 连接id
    * @param mixed $message 具体消息
    */
   public static function onMessage($client_id, $message)
   {
        // 向所有人发送 
      //Gateway::sendToAll("$client_id said $message\r\n");
       //Gateway::bindUid($client_id, )

      //获取协议名
      $index = strpos($message,"{");
      $msg_name = substr($message, 0, $index);

      //获取协议体
      $str_len = strlen($message);
      $msg_body_raw = substr($message, $index, $str_len - $index);
      $msg_body = json_decode($msg_body_raw, false);//false:解析为对象

      //不是握手协议，不打印
      if($msg_name != "handshake"){
        echo $msg_name, "=>";
        print_r($msg_body);
      }

      switch ($msg_name) {
        case 'login_c2s':
          static::handle_login($msg_body, $client_id);
          break;
        case 'startbattle_c2s':
          static::handle_startbattle($msg_body, $client_id);
          break;
        case 'finishbattle_c2s':
          static::handle_finishbattle($msg_body, $client_id);
          break;
        default:
          # code...
          echo "unhandle msg:" . $msg_name;
          break;
      }
   }
   
   /**
    * 当用户断开连接时触发
    * @param int $client_id 连接id
    */
   public static function onClose($client_id)
   {
        //static::handle_finishbattle(null, $client_id);
       // 向所有人发送 
       //GateWay::sendToAll("$client_id logout\r\n");
   }


   public static function RequestAccessToken(){
        $header = array('Content-Type: application/json');
        $postdata = array(
                     'appid'=> "tt793e0f83e602221310",
                     'secret'=>"8280be68c23b3720038550b2cbbabda00cd348e8",
                     'grant_type'=>"client_credential"
                   );
        $response = static::post("https://developer.toutiao.com/api/apps/v2/token", $header, $postdata);
        echo ($response) . "\n";
        $response_array = json_decode($response, false);
        $data_array = $response_array->data;//json_decode($response_array['data'], true);
        $GLOBALS["AccessToken"] = $data_array->access_token;

        echo "access_token:" . $GLOBALS["AccessToken"] . "\n";
   }

   # url,请求路径，postdata 请求body参数，注意是json格式
    public static function post($url,$header, $postdata)
    {
        # 初始化一个curl会话
        $ch = curl_init();
        # 启用时会发送一个常规的POST请求
        curl_setopt($ch, CURLOPT_POST, 1);
        # 需要获取的URL地址
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        # 全部数据使用HTTP协议中的"POST"操作来发送。
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($postdata));
        # 将curl_exec()获取的信息以文件流的形式返回，而不是直接输出。
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        # 一个用来设置HTTP请求头字段的数组
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header//array(
                //'User-Agent: Apifox/1.0.0 (https://apifox.com)',
                //'Content-Type: application/json',
                //'Accept: */*',
                //'Host: developer.toutiao.com',
                //'Connection: keep-alive'
            ///)
        );
        # curl_exec 执行一个cURL会话。
        $response = curl_exec($ch);
        # 关闭一个cURL会话
        curl_close($ch);
        //echo($response);
        return $response;
    }


//逻辑代码
    private static function handle_login($data, $client_id){
      $token = $data->token;
      $header = array('X-Token: '.$GLOBALS["AccessToken"],'Content-Type: application/json');
      $postdata = array('token'=> $token);
      $response = static::post("https://webcast.bytedance.com/api/webcastmate/info", $header, $postdata);
      echo $response . "\n";
      $response_obj = json_decode($response, false);

      if(isset($response_obj->errcode) && $response_obj->errcode != 0){
        // 向当前client_id发送数据 
          Gateway::sendToClient($client_id, static::wrapMsg("login_s2c", array('err_no' => $response_obj->errcode, 'reason' => $response_obj->errmsg)));
          static::RequestAccessToken();
          return;
      }

      $room_id = $response_obj->data->info->room_id;
      echo "room_id:" . $room_id . "\n";
      Gateway::bindUid($client_id, $room_id);

      // 向当前client_id发送数据 
      Gateway::sendToClient($client_id, static::wrapMsg("login_s2c", array('err_no' => 0, 'room_id' => $room_id)));
    }

    private static function handle_startbattle($data, $client_id){
      $header = array('access-token: '.$GLOBALS["AccessToken"],'Content-Type: application/json');
      $roomid = Gateway::getUidByClientId($client_id);
      $postdata = array('roomid'=> $roomid, 'appid' => "tt793e0f83e602221310", 'msg_type' => 'live_like');
      $response = static::post("https://webcast.bytedance.com/api/live_data/task/start", $header, $postdata);
      echo 'start task live_like:roomid:' . $roomid . ' ' . $response . "\n";
      $response_obj = json_decode($response, false);
      if($response_obj->err_no != 0){
          Gateway::sendToClient($client_id, static::wrapMsg("startbattle_s2c", array('err_no' => $response_obj->err_no, 'room_id' => $roomid, 'reason' => $response_obj->err_msg . " logid:" . $response_obj->logid)));
          return;
      }

      $postdata = array('roomid'=> $roomid, 'appid' => "tt793e0f83e602221310", 'msg_type' => 'live_comment');
      $response = static::post("https://webcast.bytedance.com/api/live_data/task/start", $header, $postdata);
      echo 'start task live_comment:roomid:' . $roomid . ' ' . $response . "\n";
      $response_obj = json_decode($response, false);
      if($response_obj->err_no != 0){
          Gateway::sendToClient($client_id, static::wrapMsg("startbattle_s2c", array('err_no' => $response_obj->err_no, 'room_id' => $roomid, 'reason' => $response_obj->err_msg . " logid:" . $response_obj->logid)));
          return;
      }

      $postdata = array('roomid'=> $roomid, 'appid' => "tt793e0f83e602221310", 'msg_type' => 'live_gift');
      $response = static::post("https://webcast.bytedance.com/api/live_data/task/start", $header, $postdata);
      echo 'start task live_gift:roomid:' . $roomid . ' ' . $response . "\n";
      $response_obj = json_decode($response, false);
      if($response_obj->err_no != 0){
          Gateway::sendToClient($client_id, static::wrapMsg("startbattle_s2c", array('err_no' => $response_obj->err_no, 'room_id' => $roomid, 'reason' => $response_obj->err_msg . " logid:" . $response_obj->logid)));
          return;
      }

      //static::httpsTest($roomid);
            // 向当前client_id发送数据 
      Gateway::sendToClient($client_id, static::wrapMsg("startbattle_s2c", array('err_no' => 0)));
    }

    private static function handle_finishbattle($data, $client_id){
      $header = array('access-token: '.$GLOBALS["AccessToken"],'Content-Type: application/json');
      $roomid = Gateway::getUidByClientId($client_id);
      $postdata = array('roomid'=> $roomid, 'appid' => "tt793e0f83e602221310", 'msg_type' => 'live_like');
      $response = static::post("https://webcast.bytedance.com/api/live_data/task/stop", $header, $postdata);
      echo 'stop task live_like:roomid:' . $roomid . ' ' . $response . "\n";
      $response_obj = json_decode($response, false);
      if($response_obj->err_no != 0){
          Gateway::sendToClient($client_id, static::wrapMsg("finishbattle_s2c", array('err_no' => $response_obj->err_no, 'room_id' => $roomid, 'reason' => $response_obj->err_msg . " logid:" . $response_obj->logid)));
          return;
      }

      $postdata = array('roomid'=> $roomid, 'appid' => "tt793e0f83e602221310", 'msg_type' => 'live_comment');
      $response = static::post("https://webcast.bytedance.com/api/live_data/task/stop", $header, $postdata);
      echo 'stop task live_comment:roomid:' . $roomid . ' ' . $response . "\n";
      $response_obj = json_decode($response, false);
      if($response_obj->err_no != 0){
          Gateway::sendToClient($client_id, static::wrapMsg("finishbattle_s2c", array('err_no' => $response_obj->err_no, 'room_id' => $roomid, 'reason' => $response_obj->err_msg . " logid:" . $response_obj->logid)));
          return;
      }

      $postdata = array('roomid'=> $roomid, 'appid' => "tt793e0f83e602221310", 'msg_type' => 'live_gift');
      $response = static::post("https://webcast.bytedance.com/api/live_data/task/stop", $header, $postdata);
      echo 'stop task live_gift:roomid:' . $roomid . ' ' . $response . "\n";
      $response_obj = json_decode($response, false);
      if($response_obj->err_no != 0){
          Gateway::sendToClient($client_id, static::wrapMsg("finishbattle_s2c", array('err_no' => $response_obj->err_no, 'room_id' => $roomid, 'reason' => $response_obj->err_msg . " logid:" . $response_obj->logid)));
          return;
      }

      // 向当前client_id发送数据 
      Gateway::sendToClient($client_id, static::wrapMsg("finishbattle_s2c", array('err_no' => 0)));
    }

    private static function httpsTest($roomid){
        $curl = curl_init();

        $x_nonce_str="";
        $x_timestamp="";
        $x_signature="";
        $x_roomid="";
        $x_msg_type="";
        if(false){
        foreach ($_SERVER as $name => $value) {
            if (strpos($name, 'HTTP_X_NONCE_STR') === 0) {
                $x_nonce_str = $value;
                continue;
            }
            if (strpos($name, 'HTTP_X_TIMESTAMP') === 0) {
                $x_timestamp = $value;
                continue;
            }
            if (strpos($name, 'HTTP_X_SIGNATURE') === 0) {
                $x_signature = $value;
                continue;
            }
            if (strpos($name, 'HTTP_X_ROOMID') === 0) {
                $x_roomid = $value;
                continue;
            }
            if (strpos($name, 'HTTP_X_MSG_TYPE') === 0) {
                $x_msg_type = $value;
                continue;
            }
        }
        $body = file_get_contents('php://input');

        }else{
          
                $x_nonce_str="非法字段";
                $x_timestamp="非法字段";
                $x_signature="非法字段";
                $x_roomid=$roomid;
                $x_msg_type="live_like";
                $body='[{
            "msg_id": "123456783",
            "sec_openid":"xxxx", 
            "like_num":"1",  
            "avatar_url":"xxx",    
            "nickname":"xxxx",     
            "timestamp":1649068964
        }]';
        }
        $myheaders = array(
              'x-nonce-str: '.$x_nonce_str,
              'x-timestamp: '.$x_timestamp,
              'x-signature: '.$x_signature,
              'x-roomid: '.$x_roomid,
              'x-msg-type: '.$x_msg_type,
              'User-Agent: Apifox/1.0.0 (https://apifox.com)',
              'content-type: application/json',
              'Accept: */*',
              'Host: 47.102.142.178:7654',
              'Connection: keep-alive'
           );
        curl_setopt_array($curl, array(
           CURLOPT_URL => 'http://192.168.1.113:2345',
           CURLOPT_RETURNTRANSFER => true,
           CURLOPT_ENCODING => '',
           CURLOPT_MAXREDIRS => 10,
           CURLOPT_TIMEOUT => 0,
           CURLOPT_FOLLOWLOCATION => true,
           CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
           CURLOPT_CUSTOMREQUEST => 'POST',
           CURLOPT_POSTFIELDS => $body,
           CURLOPT_HTTPHEADER => $myheaders,
        ));

        $response = curl_exec($curl);

        curl_close($curl);
        echo $response;
    }
}
